<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import {
  NAvatar,
  NButton,
  NCheckbox,
  NCheckboxGroup,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NSpace,
  NSwitch,
  NTag,
  NPopconfirm,
  NLayout,
  NLayoutSider,
  NLayoutContent,
  NTreeSelect, NSelect,NFlex
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import {formatDate, getToken, renderIcon} from '@/utils'
import { useCRUD } from '@/composables'
import api from '@/api'
import TheIcon from '@/components/icon/TheIcon.vue'
import { useUserStore } from '@/store'
const base_path = import.meta.env.VITE_BASE
import default_image from "@/assets/images/mz.jpg"

defineOptions({ name: '用户管理' })

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')

const data = reactive({
  CityData: [],
  roleOption:[]
})

const {
  modalVisible,
  modalTitle,
  modalAction,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '用户',
  initForm: {},
  doCreate: api.createUser,
  doUpdate: api.updateUser,
  doDelete: api.deleteUser,
  refresh: () => $table.value?.handlerefresh(),
})

const roleOption = ref([])
const deptOption = ref([])

onMounted(() => {
  $table.value?.handleSearch()
  api.getSpaceList().then((res) => (data.CityData = res.data))
  api.getRoleList().then((res) => (data.roleOption = res.data))

})

const columns = [
  {
    title: 'ID',
    key: 'id',
    width: 30,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '用户角色',
    key: 'role_name',
    width: 60,
    align: 'center',
    render(row) {
      return h(NTag, { type: 'primary',size:"small",bordered:false, style: { margin: '2px 3px' } }, { default: () => row.role_name })
    },
  },{
    title: '账号',
    key: 'account',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
      fixed: 'left',
  },
    {
    title: '头像/昵称',
    key: 'avatar',
    width: 80,
    align: 'left',

    render(row) {

      return h(NFlex, {},
        [h(NAvatar, {
          src: row.avatar,
          fallbackSrc: default_image,
          round: true,
          size: "medium",
        }), h(NButton, {
          size: "medium",
          dashed: true,
          type: "primary",
        }, {
          default: () => (row.name)
        })]
      )

    },
  },
  {
    title: '门店',
    key: 'space_name',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
  },

  {
    title: '上次登录时间',
    key: 'last_login',
    align: 'center',
    width: 80,
    ellipsis: { tooltip: true },
    render(row) {
      return h(
        NButton,
        { size: 'small', type: 'text', ghost: true },
        {
          default: () => (row.last_login ? formatDate(row.last_login) : null),
          icon: renderIcon('mdi:update', { size: 16 }),
        }
      )
    },
  },
  {
    title: '禁用',
    key: 'status',
    width: 50,
    align: 'center',
    render(row) {
      return h(NSwitch, {
        size: 'small',
        rubberBand: false,
        value: row.status,
        checkedValue: true,
        uncheckedValue: false,
        onUpdateValue: () => handleUpdateDisable(row),
      })
    },
  },
  {
    title: '操作',
    key: 'actions',
    width: 80,
    align: 'center',
    fixed: 'right',
    render(row) {
      return [
        withDirectives(
          h(
            NButton,
            {
              size: 'small',
              type: 'primary',
              style: 'margin-right: 8px;',
              onClick: () => {
                handleEdit(row)
              },
            },
            {
              default: () => '编辑',
              icon: renderIcon('material-symbols:edit', { size: 16 }),
            }
          ),
          []
        ),
        h(
          NPopconfirm,
          {
            onPositiveClick: () => handleDelete({ id: row.id }, false),
            onNegativeClick: () => {},
          },
          {
            trigger: () =>
              withDirectives(
                h(
                  NButton,
                  {
                    size: 'small',
                    type: 'error',
                  },
                  {
                    default: () => '删除',
                    icon: renderIcon('material-symbols:delete-outline', { size: 16 }),
                  }
                ),
                []
              ),
            default: () => h('div', {}, '确定删除该用户吗?'),
          }
        ),
      ]
    },
  },
]

// 修改用户禁用状态
async function handleUpdateDisable(row) {
  if (!row.id) return
  const userStore = useUserStore()
  if (userStore.userId === row.id) {
    $message.error('当前登录用户不可禁用！')
    return
  }
  row.status = row.status === false ? true : false
  try {
    await api.updateUser(row)
    $message?.success(row.status ? '已禁用该用户' : '已取消禁用该用户')
    $table.value?.handlerefresh()
  } catch (err) {
    // 有异常恢复原来的状态
    row.is_active = row.status === false ? true : false
  } finally {
    row.publishing = false
  }
}

let lastClickedNodeId = null


const validateAddUser = {
  name: [
    {
      required: true,
      message: '请输入名称',
      trigger: ['input', 'blur'],
    },
  ],
  pass: [
    {
      required: true,
      message: '请输入密码',
      trigger: ['input', 'blur', 'change'],
    },
  ],
  confirmPassword: [
    {
      required: true,
      message: '请再次输入密码',
      trigger: ['input'],
    },
    {
      trigger: ['blur'],
      validator: (rule, value, callback) => {
        if (value !== modalForm.value.pass) {
          callback('两次密码输入不一致')
          return
        }
        callback()
      },
    },
  ],
}
</script>

<template>
  <NLayout has-sider wh-full>
    <NLayoutContent style="background: transparent;margin-left: 20px;">
      <CommonPage show-footer title="用户列表">
        <template #action>
          <NButton  type="primary" @click="handleAdd">
            <TheIcon icon="material-symbols:add" :size="18" class="mr-5" />新建用户
          </NButton>
        </template>
        <!-- 表格 -->
        <CrudTable
          ref="$table"
          v-model:query-items="queryItems"
          :columns="columns"
          :get-data="api.getUserList"
           :scroll-x="1200"
        >
          <template #queryBar>
            <QueryBarItem label="昵称" :label-width="40">
              <NInput
                v-model:value="queryItems.name"
                clearable
                type="text"
                placeholder="请输入昵称"
                @keypress.enter="$table?.handleSearch()"
              />
            </QueryBarItem>

          </template>
        </CrudTable>

        <!-- 新增/编辑 弹窗 -->
        <CrudModal
          v-model:visible="modalVisible"
          :title="modalTitle"
          :loading="modalLoading"
          @save="handleSave"
        >
          <NForm
            ref="modalFormRef"
            label-placement="left"
            label-align="left"
            :label-width="80"
            :model="modalForm"
            :rules="validateAddUser"
          >
            <NFormItem label="所属门店" path="address_id">
              <NSelect
                v-model:value="modalForm.address_id"
                :options="data.CityData"
                placeholder="请选择所属门店"
                label-field="name"
                value-field="id"
              />
            </NFormItem>
            <NFormItem label="昵称" path="name">
              <NInput v-model:value="modalForm.name" clearable placeholder="请输入昵称" />
            </NFormItem>
            <NFormItem label="账号" path="account">
              <NInput v-model:value="modalForm.account" clearable placeholder="请输入账号" />
            </NFormItem>
            <NFormItem label="手机" path="mobile">
              <NInput v-model:value="modalForm.mobile" clearable placeholder="请输入手机" />
            </NFormItem>
            <NFormItem v-if="modalAction === 'add'" label="密码" path="pass">
              <NInput
                v-model:value="modalForm.pass"
                show-password-on="mousedown"
                type="password"
                clearable
                placeholder="请输入密码"
              />
            </NFormItem>
            <NFormItem v-if="modalAction === 'add'" label="确认密码" path="confirmPassword">
              <NInput
                v-model:value="modalForm.confirmPassword"
                show-password-on="mousedown"
                type="password"
                clearable
                placeholder="请确认密码"
              />
            </NFormItem>
            <NFormItem label="角色" path="type">
              <NSelect
                v-model:value="modalForm.type"
                :options="data.roleOption"
                placeholder="请选择角色"
                label-field="name"
                value-field="id"
              />

            </NFormItem>

<!--            <NFormItem label="禁用" path="status">-->
<!--              <NSwitch-->
<!--                v-model:value="modalForm.status"-->
<!--                :checked-value="false"-->
<!--                :unchecked-value="true"-->
<!--                :default-value="true"-->
<!--              />-->
<!--            </NFormItem>-->

          </NForm>
        </CrudModal>
      </CommonPage>
    </NLayoutContent>
  </NLayout>
  <!-- 业务页面 -->
</template>
